package com.aaa.service.impl;

import com.aaa.entity.Emp;
import com.aaa.dao.EmpDao;
import com.aaa.service.EmpService;
import com.aaa.vo.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;

/**
 * 员工表(Emp)表服务实现类
 *
 * @author makejava
 * @since 2022-11-17 14:30:44
 */
@Service("empService")
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpDao empDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Result<Emp> queryById(Integer id) {
        Emp emp = this.empDao.queryById(id);
        return Result.success(emp);
    }

    /**
     * 分页查询
     *
     * @param emp     筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Result<Page<Emp>> queryByPage(Emp emp, PageRequest pageRequest) {
        long total = this.empDao.count(emp);
        PageImpl<Emp> empPage = new PageImpl<>(this.empDao.queryAllByLimit(emp, pageRequest), pageRequest, total);
        return Result.success(empPage,"分页查询成功");
    }

    /**
     * 查询页面信息
     *
     * @param emp         筛选条件
     * @param currentPage 当前页面
     * @param pageSize    页面大小
     * @return {@link PageInfo}<{@link Emp}>
     */
    @Override
    public Result<PageInfo<Emp>> queryByPageInfo(Emp emp, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        List<Emp> empList = empDao.queryAll(emp);
        PageInfo<Emp> pageInfo = new PageInfo<>(empList);
        return Result.success(pageInfo,"查询成功并分页");
    }

    /**
     * 新增数据
     *
     * @param emp 实例对象
     * @return 实例对象
     */
    @Override
    public Result<Emp> insert(Emp emp) {
        int row = this.empDao.insertSelective(emp);
        if(row == 0){
            return Result.error("添加员工失败");
        }
        return Result.success(emp,"添加员工成功");
    }

    /**
     * 修改数据
     *
     * @param emp 实例对象
     * @return 实例对象
     */
    @Override
    public Result<Emp> update(Emp emp) {
        int i = this.empDao.update(emp);
        if(i == 0){
            return Result.error("修改成功");
        }
        Emp afterEmp = empDao.queryById(emp.getId());
        return Result.success(afterEmp,"修改成功");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public Result<Boolean> deleteById(Integer id) {
        int i = this.empDao.deleteById(id);
        if(i == 0){
            return Result.error(false,"删除失败");
        }
        return Result.success(true,"删除成功");
    }
}
